import AccessEnum from "@/access/accessEnum";
import router from "@/router";
import store from "@/store";
import { OpenAPI, UserControllerService } from "../../generated";

router.beforeEach(async (to, from, next) => {

  let curUser = store.state.user?.curUser;

  if (!curUser|| curUser?.userRole == AccessEnum.NOT_LOGIN) {
    // 获取登录对象
    const token = sessionStorage.getItem("token");
    // console.log('token', token);
    OpenAPI.TOKEN = token??"";
    if (token) {
      const res = await UserControllerService.loginByTokenUsingGet(token);
      if (res.code == 0) {
        store.dispatch('user/setCurUser', res.data)
      }
    }
  }
  curUser = store.state.user?.curUser;
  console.log('to', to);
  console.log('curUser', curUser);

  if (!curUser) {
    if (to.path == '/user/login') {
      next();
      return;
    }
  }

  // 判断当前访问页面是否需要登录
  // 如果当前页面要登录 且 用户没有登录 就返回登录页面
  const access = to.meta?.access;
  if(curUser?.userRole == AccessEnum.NOT_LOGIN && (access === AccessEnum.ADMIN || access === AccessEnum.USER)) {
    // 去登录
    next(`/user/login?redirect=${to.fullPath}`)
    return;
  }
  // 如果没权限访问当前路由
  if (to.meta?.access === AccessEnum.ADMIN) {
    if (curUser?.userRole !== AccessEnum.ADMIN) {// 不是管理员
      console.log('no admin');
      next({path:"/noAuth"})
      return;
    }else {
      console.log('is admin');
    }
  }
  next();
});